package com.zf.powerjob.worker.api_client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.powerjob.client.PowerJobClient;
import tech.powerjob.common.response.JobInfoDTO;
import tech.powerjob.common.response.ResultDTO;
import tech.powerjob.common.response.WorkflowInfoDTO;
import tech.powerjob.common.response.WorkflowInstanceInfoDTO;

/**
 * 使用 API 控制 服务端的任务和工作流
 *
 * @author Zhou Feng
 */
@RestController
@RequestMapping("/api-client")
public class ApiClientController {

    @Autowired
    @Qualifier("pjWorkerPowerJobClient")
    private PowerJobClient pjWorkerPowerJobClient;

    @GetMapping("/run")
    public String testRun() {

        // 根据 jobId 获取 job信息
        ResultDTO<JobInfoDTO> jobInfo = pjWorkerPowerJobClient.fetchJob(1L);
        System.out.println("job信息：" + jobInfo.getData());

        // 传入 jobId 来启动 job, 返回启动的job的实例id
        // ResultDTO<Long> resultDTO = pjWorkerPowerJobClient.runJob(1L, "xxx", 0);
        ResultDTO<Long> resultDTO = pjWorkerPowerJobClient.runJob(1L, "{\"xxx\":\"ccc\"}", 0);

        // 是否成功创建实例
        boolean success = resultDTO.isSuccess();

        // 获取启动的job实例的 id
        Long jobInstanceId = resultDTO.getData();
        System.out.println("job实例ID：" + jobInstanceId);

        /**
         * 根据job实例id获取job实例的状态：见 {@link tech.powerjob.common.enums.InstanceStatus} 类
         */
        ResultDTO<Integer> jobInstanceStatus = pjWorkerPowerJobClient.fetchInstanceStatus(jobInstanceId);
        System.out.println("job实例的运行状态：" + jobInstanceStatus);

        System.out.println("====================================");

        // 根据 workflowId 获取 工作流信息
        ResultDTO<WorkflowInfoDTO> wkInfo = pjWorkerPowerJobClient.fetchWorkflow(1L);
        System.out.println("工作流信息：" + wkInfo.getData());

        // 传入 workflowId 来启动 工作流, 返回启动的工作流的实例id
        // ResultDTO<Long> wk = pjWorkerPowerJobClient.runWorkflow(1L, "xxx", 0);
        ResultDTO<Long> wk = pjWorkerPowerJobClient.runWorkflow(1L, "{\"xxx\":\"ccc\"}", 0);

        // 是否成功启动
        boolean wkSuccess = wk.isSuccess();

        // 获取启动的工作流实例id
        Long wkInstanceId = wk.getData();
        System.out.println("工作流实例ID：" + wkInstanceId);

        /**
         * 根据工作流实例id获取工作流实例的信息，状态（{@link  tech.powerjob.common.enums.WorkflowInstanceStatus} 类）、触发时间、结束时间、启动参数、上下文 等等
         */
        ResultDTO<WorkflowInstanceInfoDTO> wkInstanceInfo = pjWorkerPowerJobClient.fetchWorkflowInstanceInfo(wkInstanceId);
        System.out.println("工作流实例的相关信息：" + wkInstanceInfo.getData());


        return String.format("结果：{job: %d},{workflow: %d}", jobInstanceId, wkInstanceId);
    }
}

